<?php


namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Menu;
use think\Controller;
use think\Db;

class Common extends Controller
{
    protected $adminInfo;
    public function __construct(){
        parent::__construct();
        $controller =  strtolower(request()->controller());
        $uri =  strtolower($controller.'/'.request()->action());
        session('PrevUrl'.ADMINTYPE,$uri);
        $info = session('admin'.ADMINTYPE);
        if(!$info || config('public.auth') && session('HTTP_USER_AGENT'.ADMINTYPE) != md5($_SERVER['HTTP_USER_AGENT'])){
            if(isset($info['token']))cache($info['token'],null);
            session('admin'.ADMINTYPE,null);
            if(Request()->isAjax() || Request()->isPost() ){
                echo json_encode(['code'=>30006,'msg'=>"登录过期，请重新登录"]);
                exit;
            }else{
                $this->redirect('login/login');
            }

        }

        $this->assign('admin_info',$info);

        $this->adminInfo = $info;

        if(isset($info['is_supper']) && $info['is_supper'] ==1){
            $menuList = Menu::getMenuList();

            if(ADMINTYPE ==1){
                $this->assign('menu',$menuList);
            }else{

                if(!strpos(json_encode($menuList,JSON_UNESCAPED_SLASHES),$controller)){
                    $this->redirect('index/index');
                }else{
                    $this->assign('menu',$menuList);
                }
            }


        }else{
            $menu = cache($info['token']);



            if(!$menu){
                $menu = Admin::getMenuListByRole($info['role_id']);
                cache('menu'.ADMINTYPE,$info['token'],$menu);
            }
          /*  if($uri!="auth/edit_pwd"){
                if(!strpos(serialize($menu),$uri)){
                    $this->redirect($menu[0]['router_url']);
                }
            }*/

            $this->assign('menu',$menu);
        }
        $this->assign('uri',$uri);
    }

    /**
     * @param $user_id
     * @param string $items 操作类目
     * @param $content
     * @param string $db_name
     * @param int $job_id
     * @param int $is_expire
     * @return int|string
     *
     */
    protected function  adminRecord($user_id,$items,$content,$db_name='',$job_id=0,$status=0){
        $array1 = [
            'user_id'=>$user_id,
            'items'=>$items,
            'content'=>$content,
            'admin_name'=>$this->adminInfo['username'],
            'admin_id'=>$this->adminInfo['id'],
            'create_time'=>date("Y-m-d H:i:s"),
            'db_name'=>$db_name,
            'job_id'=>$job_id,
            'status'=>$status,
            'is_expire'=>0
        ];
        return Db::name('admin_record')->insert($array1);
    }
}